/*
 * @Author: WangGuojian 1085844536@qq.com
 * @Date: 2022-09-20 12:00:52
 * @LastEditTime: 2022-09-20 12:08:49
 * @LastEditors: WangGuojian 1085844536@qq.com
 * @FilePath: \pro05-demo-all-in-one\src\main\java\com\atguigu\imperial\court\servlet\base\ModelBaseServlet.java
 * @Description:
 */
package com.atguigu.imperial.court.servlet.base;

import java.io.IOException;
import java.lang.reflect.Method;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ModelBaseServlet extends ViewBaseServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // 在 doGet() 方法中调用 doPost() 方法,这样就可以在 doPost() 方法中集中处理所有请求
        doPost(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // 1.在所有 request.getParameter()前面设置解析请求体的字符集
        request.setCharacterEncoding("UTF-8");

        // 2.从请求参数中获取 method 对应的数据
        String method = request.getParameter("method");

        // 3.通过反射调用 method 对应的方法
        // ①获取Class对象
        Class<? extends ModelBaseServlet> clazz = this.getClass();

        try {
            // ②获取method对应的Method对象
            Method methodObject = clazz.getDeclaredMethod(method, HttpServletRequest.class, HttpServletResponse.class);

            // ③打开访问权限
            methodObject.setAccessible(true);

            // ④通过Method对象调用目标方法
            methodObject.invoke(this, request, response);

        } catch (Exception e) {
            e.printStackTrace();

            // 重要提醒:为了配合 TransactionFilter 实现事务控制,捕获的异常必须抛出
            throw new RuntimeException(e);
        }
    }
}
